//
//  JCLRefreshControl.swift
//  WeiBo
//
//  Created by DDC on 2017/9/20.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

/// 设置临界点数值
fileprivate let refreshOffset:CGFloat = 80

/// 定义下拉刷新状态
///
/// - normal: 普通下拉
/// - pulling: 下拉到超过临界值
/// - willRefresh: 超过临界值准备松手
enum JCLRefreshState {
    case normal
    case pulling
    case willRefresh
}

class JCLRefreshControl: UIControl {
    
    
    
    /// 初始化控件--tableview/collectionView父控件都是scrollview
    fileprivate weak var scrollView:UIScrollView?
    /// 懒加载一个刷新页面
    fileprivate lazy var refreshView:JCLRefreshView = JCLRefreshView.refreshView()
    /// 纯代码创建调用
    init() {
        super.init(frame: CGRect())
        setUpUI()
    }
    /// XIB创建调用
    required init?(coder aDecoder: NSCoder) {
        
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        
        scrollView = sv
        // KVO监听scrollview的contentOffset
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
    }
    /// KVO监听实现的方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let sv = scrollView else {
            return
        }
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        
        // 判断height
        if height < 0 {
            return
        }
        // 判断下拉控件的状态
        if sv.isDragging {
            if height > refreshOffset && refreshView.refreshState == .normal{
                
                refreshView.refreshState = .pulling
                print("松手刷新")
            } else if height <= refreshOffset && refreshView.refreshState == .pulling{
                
                refreshView.refreshState = .normal
                print("继续下拉哦 ~")
            }
        } else {
            // 松手
            if refreshView.refreshState == .pulling {
                // 将要刷新
                refreshView.refreshState = .willRefresh
                print("将要刷新了哦~ ")
                // 将刷新视图显示出来
                guard let sv = scrollView else {
                    return
                }
                var inset = sv.contentInset
                inset.top += refreshOffset
                sv.contentInset = inset
                // 发送动作，让下拉刷新响应刷新事件~'.valueChanged'
                sendActions(for: .valueChanged)
            }
        }
        
        // 根据高度设置刷新控件的frame
        self.frame = CGRect(x: 0, y: -height, width:sv.bounds.width, height: height)
        
    }
    
    /// 移除观察者
    override func removeFromSuperview() {
        
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        super.removeFromSuperview()
    }
    
    /// 开始刷新
    func beginRefreshing() {
        
        print("begin")
        guard let sv = scrollView else {
            return
        }
        /// 判断如果是刷新状态，就跳出逻辑
        if refreshView.refreshState == .willRefresh {
            return
        }
        
        refreshView.refreshState = .willRefresh
        var inset = sv.contentInset
        inset.top += refreshOffset
        sv.contentInset = inset
    }
    
    /// 结束刷新
    func endRefreshing() {
        print("end")
        
        guard let sv = scrollView else {
            return
        }
        // 判断状态，如果不是正在刷新，直接返回,什么都不干
        if refreshView.refreshState != .willRefresh {
            return 
        }
        // 恢复状态
        refreshView.refreshState = .normal
        var inset = sv.contentInset
        inset.top -= refreshOffset
        sv.contentInset = inset
    }
    
}


extension JCLRefreshControl {
    fileprivate func setUpUI() {
        
        backgroundColor = superview?.backgroundColor
       
        /// 超出边界不显示
        /// clipsToBounds = true
     
        addSubview(refreshView)
        /// 自动布局
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item:refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height))
        
    }
}
